<?php

namespace PaymentKit\Bank\Engines;

use PaymentKit\Exceptions\RemoteException;
use PaymentKit\Bank\Interfaces\BankCardInterface;
use GuzzleHttp\Client;

class AlipayBankCard implements BankCardInterface
{
    const CARD_INFO_URL = 'https://ccdcapi.alipay.com/validateAndCacheCardInfo.json';
    const BANK_LIST = __DIR__ . '/../Source/BankList.json';
    const TYPE_LIST = __DIR__ . '/../Source/TypeList.json';

    /**
     * @param string $cardNo
     * @return bool|mixed
     * @throws RemoteException
     */
    public function getInfo($cardNo)
    {
        $params = [
            'cardNo' => $cardNo,
            'cardBinCheck' => 'true'
        ];
        $url = sprintf('%s?%s', static::CARD_INFO_URL, http_build_query($params));
        $result = $this->getRemoteUrl($url);
        $resultData = json_decode($result, true);

        if (isset($resultData['validated']) && $resultData['validated'] == true) {
            return [
                'card_no' => $resultData['key'] ?? '',
                'card_type' => $resultData['cardType'] ?? '',
                'card_bank_code' => $resultData['bank'] ?? '',
            ];
        }
        return false;
    }

    /**
     * @param $cardType
     * @return string|null
     */
    public function getCardTypeName($cardType)
    {
        $data = json_decode(file_get_contents(static::TYPE_LIST), true);
        if (!empty($data) && array_key_exists($cardType, $data)) {
            return $data[$cardType];
        }
        return null;
    }

    /**
     * @param $cardBankCode
     * @return string|null
     */
    public function getCardBankName($cardBankCode)
    {
        $data = json_decode(file_get_contents(static::BANK_LIST), true);
        if (!empty($data) && array_key_exists($cardBankCode, $data)) {
            return $data[$cardBankCode];
        }
        return null;
    }

    /**
     * @param $url
     * @return string
     * @throws RemoteException
     */
    protected function getRemoteUrl($url)
    {
        $client = new Client();
        $response = $client->request('GET', $url);
        if ($response->getStatusCode() != 200) {
            throw new RemoteException('接口访问网络出错', 2001);
        }
        return $response->getBody()->getContents();
    }
}